package cn.leaf.filter;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import static org.apache.dubbo.rpc.Constants.TOKEN_KEY;

/**
 *
 * description: dubbo接口鉴权
 *
 * @author twinkle leaf
 * @version v1.0.0
 * @since 2022-01-27 16:36:50
 * slogan: There are no two identical leaves in the world.🍃
 *
 */
@Slf4j
@Activate(group = CommonConstants.PROVIDER, value = TOKEN_KEY)
@RequiredArgsConstructor
public class DubboFilter implements Filter {

    /**
     * dubbo接口鉴权，校验消费者token
     * @param invoker invoker
     * @param invocation invocation
     * @return {@link org.apache.dubbo.rpc.Result}
     * @throws RpcException rpc exception
     */
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        if (!invocation.getAttachment(TOKEN_KEY).equals("1")) {
            log.error("dubbo 接口鉴权失败");
            throw new RpcException("dubbo 接口鉴权失败");
        }
        log.info("dubbo 接口鉴权成功...");
        return invoker.invoke(invocation);
    }
}
